<?php 
class Zen_Behavior_ManyToMany extends Zen_Behavior_Abstract 
{
	protected $_main_field = null;
	
	protected $_main_rel_field = null;
	
	protected $_related_table = null;
	
	protected $_rel_field = null;
	
	public function __construct(){
		if (! isset($this->_main_field)) 		
			throw new Exception('Main_field is not defined');
		if (! isset($this->_main_rel_field)) 	
			throw new Exception('Main_rel_field is not defined');
		if (! isset($this->_related_table)) 	
			throw new Exception('Related_table is not defined');
		if (! isset($this->_rel_field)) 		
			throw new Exception('Rel_field is not defined');
	}
	
	protected function filterField($field) {
		foreach ($field as $key => $value ) 
			if (!is_numeric ($value)) unset($field[$key]);
		return $field;
	}
	
	public function afterCreate($params){
		$id = $params['id'];
		if(isset($params[$this->_main_field])){
			$field = $this->filterField($params[$this->_main_field]);
			if ($field) {
				$table=new Zend_Db_Table($this->_related_table);
				foreach ($field as $item ){
					$table->createRow(array(
							$this->_main_rel_field=>$id,
							$this->_rel_field=>$item
						))->save();
				}	
			}
		}
		return $params;
	}
	
	public function afterRead($params){
		$table=new Zend_Db_Table($this->_related_table);
		$id = $params['id'];
		$items=$table->select()
						->from($table,array($this->_rel_field))
						->where($this->_main_rel_field . '=?',$id)
						->query()->fetchAll();	
		if($items){
			$params[$this->_main_field] = array();
			foreach ($items as $item){
				$params[$this->_main_field][]=$item[$this->_rel_field];
			}
		}
		return $params;
	}
	
	public function beforeUpdate($params){
		$id = $params['id'];
		$table=new Zend_Db_Table($this->_related_table);
		$table->delete( $this->_main_rel_field . "=$id");
		return $this->afterCreate($params);
	}
	
	public function beforeDelete($params){
		$id = $params['id'];
		$table=new Zend_Db_Table($this->_related_table);
		$where = $this->_main_rel_field . "=$id";
		$table->delete( $where);
		return $params;
	}
}